Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Stack → Stack in Java

Stack

Stack in Java

Stack: LIFO (Last-In-First-Out) Data Structure

Stack is a class that implements the List interface in Java. It follows the LIFO (Last-In-First-Out) principle, meaning the element added last is the first element to be removed. It's a simple data structure that mimics a real-world stack, where you can only add or remove elements from the top.

Characteristics

LIFO Behavior: Stack operations adhere to LIFO (Last-In-First-Out) order. Elements are added using push(obj) and removed using pop(). Extends Vector (Legacy): Stack inherits from Vector, which provides functionalities like dynamic resizing of the underlying array. However, similar to Vector, Stack's thread-safety mechanisms are generally considered less favorable in modern Java due to performance overhead. Limited Functionality: Compared to a more general-purpose List like ArrayList, Stack offers a limited set of methods focused on pushing and popping elements.

Stack benefits

Function call stacks: Stacks are used internally by the JVM to manage function calls (method invocation). Expression evaluation: Stacks are helpful in evaluating expressions that follow postfix notation (operand-operator order) by keeping track of operands until the operator is encountered. Backtracking algorithms: Some backtracking algorithms utilize stacks to explore different paths in a search and keep track of the current state. Undo/redo functionality: Stacks can be used to implement undo/redo mechanisms in applications, where the last actions can be reversed by popping elements from the stack.

Java's Stack Class

Java's java.util.Stack class implements the stack functionality. It inherits from the Vector class and provides methods for stack operations. However, due to potential synchronization issues, Stack is generally considered less preferable than other options like Deque for modern Java development. Let's see how to initialize and declare a Stack: Import
Import Stack syntaximport java.util.Stack;
This line imports the Stack class from the java.util package.

Declaration

Stack declaration syntaxStack<DataType> myStack;
This declares a variable named myStack of type Stack. The <DataType> placeholder specifies the type of elements the stack will hold. For example, Stack<String> for strings or Stack<Integer> for integers.

Initialization

There are two ways to initialize a Stack: Default constructor This creates an empty Stack object.
Creating an empty stackmyStack = new Stack<DataType>();

Adding elements during creation (Java 10+)

Adding elements during creationStack<String> greetings = Stack.of("Hello", "Hi", "Welcome");
This is a shorthand approach using the Stack.of() method (available since Java 10) to create a Stack and add initial elements.
Notes: ⯄ Stack follows LIFO (Last-In-First-Out) principle. ⯄ The push() method adds elements to the top of the stack. ⯄ The pop() method removes and returns the top element. ⯄ The peek() method returns the top element without removing it. ⯄ Consider using Deque for a more modern and versatile LIFO data structure implementation in Java.

Examples of Stack

1. String Stack
Stack example using string elements in java import java.util.Stack; public class Main { public static void main(String[] args) { // Create a Stack to store Strings Stack<String> colors = new Stack<String>(); // Push elements (add to the top) colors.push("Red"); colors.push("Green"); colors.push("Blue"); // Print the Stack (elements will be in reverse order of pushing) System.out.println(colors); // Access elements String topColor = colors.peek(); System.out.println("Top color: " + topColor); String removedColor = colors.pop(); System.out.println("Removed color: " + removedColor); System.out.println(colors); } }

Output

[Red, Green, Blue] Top color: Blue Removed color: Blue [Red, Green]

2. Integer Stack
Stack example using integers elements in java import java.util.Stack; public class Main { public static void main(String[] args) { // Create a Stack to store Integers (use Integer wrapper class) Stack<Integer> numbers = new Stack<Integer>(); // Push elements numbers.push(10); numbers.push(20); numbers.push(30); // Print the Stack System.out.println(numbers); // Access elements int topNumber = numbers.peek(); System.out.println("Top number: " + topNumber); int removedNumber = numbers.pop(); System.out.println("Removed number: " + removedNumber); System.out.println(numbers); } }

Output

[10, 20, 30] Top number: 30 Removed number: 30 [10, 20]

3. Custom Object Stack Now, we can use Stack with Product objects:
Stack example using object as elements in java import java.util.Stack; class Product { String name; double price; public Product(String name, double price){ this.name=name; this.price=price; } } public class Main { public static void main(String[] args) { // Create a Stack to store Product objects Stack<Product> products = new Stack<>(); // Create Product objects and push them Product p1 = new Product("Shirt",19.99); products.push(p1); Product p2 = new Product("Shoe",20.50); products.push(p2); // Access elements (use peek() to avoid removing) Product topProduct = products.peek(); System.out.println("Top product name: " + topProduct.name); // Loop through the stack using pop() to remove and process elements (implement in a loop) } }

Output

Top product name: Shoe

Remember, for modern Java development, consider using Deque from the java.util package, which provides a more versatile LIFO data structure implementation that avoids the potential drawbacks of Stack. In Conclusion: Stack is a fundamental data structure that excels in LIFO operations. If your application requires a last-in-first-out behavior for element access, Stack is a suitable choice. However, for more versatile list operations or thread-safety considerations in modern Java, explore alternative collection options like ArrayList or concurrent collections.

Tutorials